// Copyright 2023 Guo Tingjin(ericple)

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import HAPV_CONSTANTS from "../hapvConstants";
import clone from "../utils/clone";
import path from 'path';

class ArgumentParser {
    private static _argumentMap: Map<string, string> = new Map();
    private static checkNecessaryArgs(): boolean {
        let i = -1;
        let keys = this._argumentMap.keys();
        let result = true;
        while (i < HAPV_CONSTANTS.NECESSARY_ARGUMENTS.length - 1) {
            i++;
            let temp = false;
            for (let k of keys) {
                if (k == HAPV_CONSTANTS.NECESSARY_ARGUMENTS[i]) {
                    temp = true;
                }
            }
            if (!temp) {
                console.error(`Error: argument missing: ${HAPV_CONSTANTS.NECESSARY_ARGUMENTS[i]}`);
                result = false;
            }
        }
        return result;
    }
    public static Parse(): Map<string, string> {
        this._argumentMap.set(HAPV_CONSTANTS.NAMED_ARGUMENTS.WORK_DIR, path.join(HAPV_CONSTANTS.NAMED_ARGUMENTS.WORK_DIR, '..'));
        const argsArray = clone(process.argv.slice(2));
        let index: number = -1;
        while (index < argsArray.length - 1) {
            ++index;
            if (argsArray[index].startsWith('--')) {
                if (!HAPV_CONSTANTS.ACCEPTABLE_ARGUMENTS.includes(argsArray[index])) {
                    console.warn(`Warning: unsupport argument${argsArray[index]}`);
                    continue;
                }
                if (argsArray[index + 1] && argsArray[index + 1].startsWith('--')) {
                    this._argumentMap.set(argsArray[index], '');
                    continue;
                }
                this._argumentMap.set(argsArray[index], argsArray[++index]);
            }
        }
        if (!this.checkNecessaryArgs()) {
            process.exit(-1);
        }
        return this._argumentMap;
    }
}

export default ArgumentParser;